package idv.arthur.work;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class IsSubmitTRable
 */
//@WebServlet(description = "檢查是否可以送審測試結果", urlPatterns = { "/IsSubmitTRable" })
public class IsSubmitTRable extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IsSubmitTRable() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		
		Widgets wid = new Widgets();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String strSQL = "SELECT MAX(ver) FROM tms_mrtcmapping WHERE tpid=? AND mrid=?";
		int returnResult = 2;
		
		int tpid = Integer.parseInt(request.getParameter("tpid"));
		String mrid = request.getParameter("mrid");

		try {
			conn = wid.getConn(true);
			
			/** 先把目前的版次給記錄下來 **/
			ps = conn.prepareStatement(strSQL);
			ps.setInt(1, tpid);
			ps.setString(2, mrid);
			rs = ps.executeQuery();
			rs.next();
			int ver = rs.getInt(1);	
			returnResult = Integer.parseInt(wid.checkTRsubmittAble(tpid, mrid, ver, conn, ps, rs));
		} catch (SQLException e) {
			wid.keepErrorMes(conn, ps, e,"", true);
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(e.toString());
			}
		}
		
		response.setContentType("application/text");
		response.getWriter().write(String.valueOf(returnResult));
	}

}
